package com.edu.atams.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.edu.atams.common.lang.Result;
import com.edu.atams.entity.Parent;
import com.edu.atams.entity.Student;
import com.edu.atams.entity.SysUser;
import com.edu.atams.entity.Teacher;
import com.edu.atams.security.AccountUser;
import com.edu.atams.service.ParentService;
import com.edu.atams.service.StudentService;
import com.edu.atams.service.SysUserService;
import com.edu.atams.service.TeacherService;
import com.edu.atams.utils.JwtUtils;
import com.edu.atams.utils.WeChatUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;


@Slf4j
@RestController
public class WeChatLoginController extends BaseController{

    @Autowired
    WeChatUtil weChatUtil;

    @Autowired
    SysUserService sysUserService;

    @Autowired
    StudentService studentService;

    @Autowired
    TeacherService teacherService;

    @Autowired
    ParentService parentService;

    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

   /* @GetMapping("/onWXLogin")
    public Result onWXLogin(String code) {
        String openid = weChatUtil.getOpenid(code);
        System.out.println(openid);
        // 如果在数据库中查询不到，则表明该用户是没有注册绑定指定登录账号的，要求输入账号信息将openid绑定到指定账号
        SysUser sysUser = sysUserService.getOne(new QueryWrapper<SysUser>().eq("openid", openid));
        if (sysUser == null) {
            return Result.fail("当前暂未注册绑定，请先绑定", openid);
        } else {
            switch (sysUser.getRoleType()) {
                case 1:
                    return Result.succ(studentService.getOne(new QueryWrapper<Student>().eq("user_id", sysUser.getId())));
                case 2:
                    return Result.succ(teacherService.getOne(new QueryWrapper<Teacher>().eq("user_id", sysUser.getId())));
                case 3:
                    return Result.succ(parentService.getOne(new QueryWrapper<Parent>().eq("user_id", sysUser.getId())));
            }
        }
        return Result.succ("");
    }*/

    @GetMapping("/onWXLogin")
    public Result onWXLogin(String code, HttpServletResponse httpServletResponse) {
        String openid = weChatUtil.getOpenid(code);
        System.out.println(openid);
        // 如果在数据库中查询不到，则表明该用户是没有注册绑定指定登录账号的，要求输入账号信息将openid绑定到指定账号
        SysUser su = sysUserService.getOne(new QueryWrapper<SysUser>().eq("openid", openid));
        if (su == null) {
            return Result.fail("当前暂未注册绑定，请先绑定", openid);
        } else {
            String jwt = jwtUtils.generateToken(su.getUsername());
            log.info("小程序生成JWT成功！username---{}，userID---{}，JWT---{}",su.getUsername(),su.getId(),jwt);
            httpServletResponse.setHeader("Authorization",jwt);
            if (su.getRoleType() == 2){
                Teacher teacher = teacherService.getOne(new QueryWrapper<Teacher>().eq("schoolNo", su.getUsername()));
                return Result.succ(
                        MapUtil.builder()
                                .put("name",teacher.getName())
                                .put("id",teacher.getId())
                                .put("userId",su.getId())
                                .put("roleType",su.getRoleType())
                                .build()
                );
            }else if (su.getRoleType() == 1){
                Student student = studentService.getOne(new QueryWrapper<Student>().eq("schoolNo", su.getUsername()));
                return Result.succ(
                        MapUtil.builder()
                                .put("name",student.getName())
                                .put("id",student.getId())
                                .put("userId",su.getId())
                                .put("roleType",su.getRoleType())
                                .build()
                );
            }else {
                Parent parent = parentService.getOne(new QueryWrapper<Parent>().eq("tel", su.getUsername()));
                return Result.succ(
                        MapUtil.builder()
                                .put("name",parent.getName())
                                .put("id",parent.getId())
                                .put("userId",su.getId())
                                .put("roleType",su.getRoleType())
                                .build()
                );
            }
        }
    }

    @PostMapping("/onWXRegister")
    public Result onWXRegister(@RequestBody SysUser sysUser, HttpServletResponse httpServletResponse) {

        SysUser su = sysUserService.getOne(new QueryWrapper<SysUser>()
                .eq("username", sysUser.getUsername())
                .eq("role_type", sysUser.getRoleType()));
        if (su == null || !bCryptPasswordEncoder.matches(sysUser.getPassword(),su.getPassword())) {
            return Result.fail("未存在该用户");
        } else {
            //生成jwt，并返回
            String jwt = jwtUtils.generateToken(su.getUsername());
            log.info("小程序生成JWT成功！username---{}，userID---{}，JWT---{}",su.getUsername(),su.getId(),jwt);
            httpServletResponse.setHeader("Authorization",jwt);
            su.setOpenid(weChatUtil.getOpenid(sysUser.getOpenid()));
            sysUserService.updateById(su);

            if (su.getRoleType() == 2){
                Teacher teacher = teacherService.getOne(new QueryWrapper<Teacher>().eq("schoolNo", su.getUsername()));
                return Result.succ(
                        MapUtil.builder()
                                .put("name",teacher.getName())
                                .put("id",teacher.getId())
                                .put("userId",su.getId())
                                .put("roleType",su.getRoleType())
                                .build()
                );
            }else if (su.getRoleType() == 1){
                Student student = studentService.getOne(new QueryWrapper<Student>().eq("schoolNo", su.getUsername()));
                return Result.succ(
                        MapUtil.builder()
                                .put("name",student.getName())
                                .put("id",student.getId())
                                .put("userId",su.getId())
                                .put("roleType",su.getRoleType())
                                .build()
                );
            }else {
                Parent parent = parentService.getOne(new QueryWrapper<Parent>().eq("tel", su.getUsername()));
                return Result.succ(
                        MapUtil.builder()
                                .put("name",parent.getName())
                                .put("id",parent.getId())
                                .put("userId",su.getId())
                                .put("roleType",su.getRoleType())
                                .build()
                );
            }

        }
    }
}
